package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录 登出 三合一.
 */
@RestController
@RequestMapping("user")
public class UserLoginController {

    @Reference(timeout = 3000,retries = 1, check = false)
    private IKaptchaService iKaptchaService;

    @Reference(timeout = 3000,retries = 1, check = false)
    private ILoginService loginService;

    public static String ACCESS_TOKEN = "access_token";

    /**
     * 用户登录
     */
    @Anoymous
    @PostMapping("login")
    public ResponseData userLogin(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse httpServletResponse){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        //验证验证码是否有效正确
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setErrorMsg(kaptchaCodeResponse.getMsg());
        }


        //代码走到这里,证明有access_token,以及验证码有效
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse response = loginService.userLogin(userLoginRequest);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setErrorMsg(response.getMsg());
        }

        Cookie cookie = CookieUtil.genCookie(ACCESS_TOKEN, response.getToken(), "/", 7 * 24 * 60 * 60);
        httpServletResponse.addCookie(cookie);
        return new ResponseUtil().setData(response);
    }

    @GetMapping("login")
    public ResponseData validationUserIsLogin(HttpServletRequest request){
        try {
            String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
            JSONObject object = JSON.parseObject(userInfo);
            long uid = Long.parseLong(object.get("uid").toString());
            String username =object.get("username").toString();

            Object fileMap = object.get("file");
            String file;
            if (fileMap == null){
                file = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"; //默认头像
            }else {
                file = fileMap.toString();
            }
            return new ResponseUtil().setData(new ValidationUserIsLoginResponse(username,uid,file));
        } catch (NullPointerException e) {
            return new ResponseUtil().setData("Token失效");
        }
    }

    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request,HttpServletResponse response){

        Cookie cookie = CookieUtil.genCookie(ACCESS_TOKEN,  null, "/", 60);
        //cookie.setMaxAge(0);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return new ResponseUtil().setData(null);
    }

}
